package com.myCommunity.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.myCommunity.dao.ForumDao;
import com.myCommunity.dao.HibernateUtil;
import com.myCommunity.entity.Forum;

public class ForumDaoImpl implements ForumDao {

	public List<Forum> getAllForum() {
		Session sess = null ;
		try{
			sess = HibernateUtil.openSession();
			Query query = sess.createQuery("from Forum");
			return query.list();
		}finally{
			if(sess != null)
				sess.close();
		}
	}
	

	public Forum getForumById(int id) {
		Session sess = null ;
		try{
			sess = HibernateUtil.openSession();
			return (Forum)sess.get(Forum.class, id);
		}finally{
			if(sess != null)
				sess.close();
		}
	}


	public List<Forum> getForumLevel() {
		List<Forum> list = this.getAllForum();
		List<Forum> parent = new ArrayList<Forum>();
		for(Forum f : list){
			if(f.getParentId()==null){
				parent.add(f);
				for(Forum c : list ){
					if(c.getParentId() != null && c.getParentId().equals(f.getId()))
						f.getChildren().add(c);
				}
			}
		}
		return parent;
	}
	
	public static void main(String[] args) {
		for(Forum f : new ForumDaoImpl().getForumLevel()){
			System.out.println(f.getName());
			for(Forum c : f.getChildren())
				System.out.println("\t"+c.getName());
		}
	}

}
